﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace SendKeyTo.Core
{
    public class Keybd_Event
    {
        [DllImport("USER32.DLL")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  //导入寻找windows窗体的方法
        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);  //导入为windows窗体设置焦点的方法
        [DllImport("USER32.DLL")]
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);  //导入模拟键盘的方法

        public static void KeyDown(IntPtr calculatorHandle, Keybd_Enum key)
        {
            try
            {
                SetForegroundWindow(calculatorHandle);
                keybd_event((byte)key, 0, 0, 0);
            }
            catch (Exception ex)
            {
                throw new Keybd_Exception(ex.Message);
            }
        }

        public static void KeyUp(IntPtr calculatorHandle, Keybd_Enum key)
        {
            try
            {
                SetForegroundWindow(calculatorHandle);
                keybd_event((byte)key, 0, 2, 0);
            }
            catch (Exception ex)
            {
                throw new Keybd_Exception(ex.Message);
            }
        }

        public static void KeyDown(Keybd_Enum key)
        {
            try
            {
                keybd_event((byte)key, 0, 0, 0);
            }
            catch (Exception ex)
            {
                throw new Keybd_Exception(ex.Message);
            }
        }

        public static void KeyUp(Keybd_Enum key)
        {
            try
            {
                keybd_event((byte)key, 0, 2, 0);
            }
            catch (Exception ex)
            {
                throw new Keybd_Exception(ex.Message);
            }
        }

        #region back

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    IntPtr calculatorHandle = FindWindow(null, "aaa.txt - 记事本");
        //    //判断是否找到了该窗体
        //    if (calculatorHandle == IntPtr.Zero)
        //    {
        //        MessageBox.Show("Calculator is not running.");
        //        return;
        //    }
        //    Clipboard.SetText("第三方");

        //    SetForegroundWindow(calculatorHandle);          
        //    keybd_event(0x11, 0, 0, 0);
        //    keybd_event(86, 0, 0, 0);
        //    keybd_event(0x11, 0, 2, 0);
        //    keybd_event(86, 0, 2, 0);
        //}

        //keybd_event方法的第一个参数值有：（例如：keybd_event(0x11, 0, 0, 0)是CTRL 键 按下  keybd_event(0x11, 0, 2, 0)是CTRL 键 松开）

        #endregion
    }
}
